const path = require('path');
const moment = require('moment');
const env = require('./env')
const fs = require('fs');

const log = (msg, type) => {
  const name = `log-${type}-${moment().format('YYYYMMDD')}`;
  const filePath = `${path.resolve(env.logPath)}/${name}`;
  msg = `[${moment().format('YYYY-MM-DD HH:mm:ss')}]` + msg;
  fs.appendFile(filePath, msg, (err) => {
    if (err) console.log(err);
  });
};
const logger = async (ctx, next) => {
  let body = JSON.stringify(ctx.request.body);
  let query = JSON.stringify(ctx.request.query);
  try {
    log(` ${ctx.method} ${ctx.request.originalUrl} ${ctx.request.headers['x-real-ip'] || ctx.request.headers['x-forwarded-for']} ${body === '{}' ? '' : body} ${query === '{}' ? '' : query} \n`, 'request');
    await next();
  } catch (error) {
    console.log(error);
    log(` ${ctx.request.headers['x-real-ip'] || ctx.request.headers['x-forwarded-for']} [msg] ${error.message} [stack] ${error.stack} \n`, 'error');
  }
}

module.exports = {
  log,
  logger
}